<?php
/*------------------------------------------------------------------------
 * 文件管理模型
 * 	
 * Created on 2014-09-17
 *
 * Author: hwc123 <hwc123@139.com>
 * 
 * Copyright (c) 2014 http://www.suncco.com All rights reserved.
 * ------------------------------------------------------------------------
 */
namespace Api\Model;
use Think\Model;

class FileModel extends Model{
	/**
	 * 获取上传文件信息
	 * @param  [type] $file_id 文件ID
	 */
	public function get_file_info($file_id){
		$data = $this->where(array('id' => $file_id))->find();
		$data['file_id']  = $data['id'];
		$data['file_url'] = $this->get_path($file_id);
		unset($data['id']);

		return $data['file_id'] > 0 ? $data : array();
	}
	/**
	 * 获取文件清单信息
	 * @param  [type] $file_ids 文件ID，多个以逗号分隔
	 */
	public function get_file_list($file_ids){
		if(!$file_ids){
			return array();
		}
		$where['id'] = array('in', $file_ids);
		$list = $this->where($where)->select();
		foreach ($list as $rs) {
			$rs['file_id']     = $rs['id'];
			$rs['file_url']    = $this->get_path($rs['id']);
			$rs['upload_time'] = date('Y-m-d H:i:s', $rs['create_time']);
			unset($rs['id']);
			$new_list[] = $rs;
		}
		return $new_list;
	}
	/**
	 * 获取文件的完整地址
	 * @param  [type] $file_id 文件ID
	 * @return [type]          文件完整地址
	 */
	public function get_path($file_id, $width = '', $height = '', $watermark = false){
	    //默认图片
	    $default_file = '/Public/Images/default.png';
	    //获取图片相对地址
	    if(is_numeric($file_id)){
			$images_file = $this->where(array('id' => $file_id))->getField('filepath');
	    }else{
	    	$images_file = $file_id ? '/Public/Images/' . $file_id : '';
	    }
	    $domain = C('FILE_SERVICE_DOMAIN');
	    $domain = $domain ? $domain : DOMAIN_PATH;
	    //返回图片完整地址
		$images_url = $domain . ($images_file ? $images_file : $default_file);

		if($watermark && $images_file){
			$img_info       = pathinfo('.' . $images_file);
			$watermark_path = './Uploads/watermark/';
			$newfile        = $watermark_path . md5($images_file) . '.' . $img_info['extension'];
			//水印LOGO文件
			$water_img      = './Public/Images/watermark.png';

			if(file_exists($watermark_path) == false){
				mkdir($watermark_path, 0700);
			}
			$water_img_exists   = file_exists($water_img);
			$newfile_exists     = file_exists($newfile);
			$images_file_exists = file_exists('.' . $images_file);
			if($water_img_exists && $images_file_exists && $newfile_exists == false){
				$water_info = pathinfo($water_img);
				$size       = getimagesize($water_img);
				$params     = array(
					'watermarkstatus'    => 9,
					'watermarkminwidth'  => $size[0],
					'watermarkminheight' => $size[1],
					'watermarktype'      => strtolower($water_info['extension']),
					'watermarkfile'      => $water_img,
					'watermarktrans'     => 0,
					'watermarkquality'   => 100
				);
				import("Water",'Public/Class/suncco/');
				$w = new Water($params);
				$w->Watermark('.' . $images_file, $newfile);
				$images_url = $domain . str_replace('./','/',$newfile);
			}
			if($newfile_exists){
				$images_url = $domain . str_replace('./','/',$newfile);
			}
		}

	    if($width && $height){
	    	$images_url = $images_url . '!w' . $width . '_h' . $height . '.jpg';
	    }
	    return $images_url;
	}
	/**
	 * 获取文件上传文件完整地址
	 * @param  string $file_id 文件ID
	 */
	public function get_upload_filepath($file_id=''){
		if(!$file_id){
			return '';
		}
		//获取文件上传信息
		$where['id'] = $file_id;
		$file_info = D('File')->where($where)->find();
		//上传文件地址
		$app_file  = '.'.$file_info['filepath'];
		$app_file_info = pathinfo($app_file);
		//上传目录
		$dirname = $app_file_info['dirname'];
		//上传原文件地址
		$newfile = $dirname . '/' . $file_info['filename'];
		//复制一份以上传原文件名
		if(file_exists($newfile) == false && file_exists($app_file)){
			copy($app_file,$newfile);
		}
		//两个文件不一致
		if(md5_file($newfile) != md5_file($app_file) && file_exists($newfile) && file_exists($app_file)){
			copy($app_file,$newfile);
		}
		$newfile  = str_replace('./', '/', $newfile);
		$domain   = C('FILE_SERVICE_DOMAIN');
		$domain   = $domain ? $domain : DOMAIN_PATH;
		$file_url = $domain.$newfile;
		return $file_url;
	}
	public function qrcode($content,$type='order'){
		import("QRcode",'Public/Class/other/');
		$qrcode_path = '/Uploads/images/qrcode/'.$type.'/';
		if(file_exists($qrcode_path)==false){
			mkdir($qrcode_path,0700,true);
		}
		$is_create = false;
		$qrcode_file = $qrcode_path.md5($content).'.png';
		if(file_exists($qrcode_file)==false){
			$is_create = true;
		}else{
			clearstatcache();
			$filetime = filemtime($qrcode_file);
			$time = time()-$filetime;
			if($time>60*60){
				$is_create = true;
				unlink($qrcode_file);
			}
		}
		if($is_create){
			$qrcode = QRcode::png($content, $qrcode_file,QR_ECLEVEL_L,10,0);
		}
		$domain = C('FILE_SERVICE_DOMAIN');
		return $domain.'/'.$qrcode_file;
	}
	/**
	 * 上传单个文件
	 * @param  string $user_id   用户ID
	 * @param  string $path      保存路径
	 * @param  string $filefield 上传字段
	 * @return [type]            文件ID
	 */
	public function upload($user_id = '', $path = 'file', $filefield = 'file'){
		if(empty($_FILES)){
			return 0;
		}
		$FILES    = $_FILES[$filefield];
		$tempFile = $FILES['tmp_name'];
		$pathinfo = pathinfo($FILES['name']);
		$ext      = $pathinfo['extension'];
		if(in_array($ext, array('php', 'asp', 'html', 'htm', 'sh', 'bash'))){
			return -1;
		}

		$filename   = md5($pathinfo['basename'].uniqid()).".".$ext;
		$targetPath = $_SERVER['DOCUMENT_ROOT'] . '/';
		$newfile    = "/Uploads/".$path.'/'.$filename;
		$targetFile = str_replace('//','/',$targetPath).$newfile;
		mkdir(str_replace($filename,'',$targetFile),0777,true);
		if (@move_uploaded_file($tempFile,$targetFile)){
			$fileinfo['filename']    = $pathinfo['basename'];//原文件名
			$fileinfo['savename']    = $filename;//保存文件名
			$fileinfo['filepath']    = $newfile;
			$fileinfo['ext']         = $ext;
			$fileinfo['size']        = $FILES['size'];
			$fileinfo['create_time'] = time();
			$fileinfo['user_id']     = $user_id;
			$model = D('File');
			$model->add($fileinfo);
			//文件ID
			$file_id = $model->getLastInsID();

			return $file_id;
		}else{
		 	return -1;
		}
	}
	/**
	 * 上传多个文件
	 * @param  string $user_id   用户ID
	 * @param  string $path      保存路径
	 * @return [type]            文件ID，多个以逗号分隔
	 */
	public function upload_multi($user_id = '', $path = 'file', $is_return_one = false){
		if(empty($_FILES)){
			return 0;
		}
		$file_id = '';
		foreach ($_FILES as $FILES) {
			$tempFile = $FILES['tmp_name'];
			$pathinfo = pathinfo($FILES['name']);
			$ext      = $pathinfo['extension'];

			$filename   = md5($pathinfo['basename'].uniqid()).".".$ext;
			$targetPath = $_SERVER['DOCUMENT_ROOT'] . '/';
			$newfile    = "/Uploads/".$path.'/'.$filename;
			$targetFile = str_replace('//','/',$targetPath).$newfile;
			mkdir(str_replace($filename,'',$targetFile),0777,true);
			if (@move_uploaded_file($tempFile,$targetFile)){
				$fileinfo['filename']    = $pathinfo['basename'];//原文件名
				$fileinfo['savename']    = $filename;//保存文件名
				$fileinfo['filepath']    = $newfile;
				$fileinfo['ext']         = $ext;
				$fileinfo['size']        = $FILES['size'];
				$fileinfo['create_time'] = time();
				$fileinfo['user_id']     = $user_id;
				$model = D('File');
				$model->add($fileinfo);
				//文件ID
				$file_id[] = $model->getLastInsID();
			}
		}
		if(!empty($file_id)){
			$file_ids = implode(',', $file_id);
			if($is_return_one){
				$file_ids = $file_id[0];
			}
		}
		return $file_ids ? $file_ids : 0;
	}
	/**
	 * 下载远程图片到本地
	 */
	public function down_remote_img($imgurl,$save_path='head',$user_id=''){
		$file_id = 0;
		if($imgurl){
			//保存路径
			$filepath = 'Uploads/'.$save_path.'/';
			//判断目录是否存在，不存在则创建
			if(file_exists($filepath) == false){
				mkdir($filepath,0700,true);
			}
			//文件路径信息
			$img_info  = pathinfo($imgurl);
			$extend    = $img_info['extension'];
			$savename  = md5($imgurl).'.'.$extend;
			$local_url = $filepath.md5($imgurl).'.'.$extend;
			if(!file_exists($local_url)){
				$http = new \Org\Net\Http();
				$http->curlDownload($imgurl,$local_url);
				if(!$extend){
					$image_type = exif_imagetype($local_url);
					$extend = image_type_to_extension($image_type, false);
					copy($local_url,$local_url.$extend);
					unlink($local_url);
					$local_url = $local_url.$extend;
					$savename = $savename.$extend;
				}

				$data['filename']    = $img_info['basename'];//原文件名
				$data['savename']    = $savename;//保存文件名
				$data['filepath']    = '/'.$local_url;
				$data['ext']         = $extend;
				$data['size']        = filesize($local_url);
				$data['create_time'] = time();
				$data['user_id']     = $user_id ? $user_id : 0;
				D('File')->add($data);
				//文件ID
				$file_id = D('File')->getLastInsID();
			}
		}
		return $file_id;
	}
	/**
	 * 图片裁切
	 * @param  [type]  $file_id 文件ID
	 * @param  integer $x1      [description]
	 * @param  integer $y1      [description]
	 * @param  integer $x2      [description]
	 * @param  integer $y2      [description]
	 * @return [type]           [description]
	 */
	public function crop($user_id = '', $file_id, $x1 = 0, $y1 = 0, $x2 = 100, $y2 = 100, $width = 100, $height = 100){
		if(!$file_id){
			return false;
		}
		//获取原文件完整路径
		$source_path = $this->where(array('id' => $file_id))->getField('filepath');
		if(!$source_path){
			return false;
		}
		$source_info = pathinfo($source_path);
		$source_path = str_replace('/Uploads', 'Uploads', $source_path);
		//获取原图分辨率大小
		list($owidth,$oheight) = getimagesize($source_path);
		//计算X比率
		$x_ratio = $owidth / ($width);
		//计算Y比率
		$y_ratio = $oheight / ($height);

		$new_x1 = abs($x_ratio * $x1);
		$new_x2 = abs($x_ratio * $x2);
		$new_y1 = abs($y_ratio * $y1);
		$new_y2 = abs($y_ratio * $y2);

		// var_dump($x1,$y1,$x2,$y2,'-----');
		// var_dump($x_ratio,$y_ratio,'-----');
		// var_dump($width,$height,$new_x1,$new_y1,$new_x2,$new_y2);exit;

		//保存文件名称
		$filename = md5($source_path . $new_x1 . $new_y1 . $new_x2 . $new_y2) . '.' . $source_info['extension'];
		//保存文件路径
		$filepath = 'Uploads/crop/' . date('Ymd') . '/';
		if(!file_exists($filepath)){
			mkdir($filepath,0700,true);
		}
		//保存文件完整路径及名称
		$target_path = $filepath . $filename;
		//导入图片裁切包
		import("Zebra_Image",'Public/Class/Other');
		$image = new \Zebra_Image();
		$image->source_path = $source_path;//源文件
		$image->target_path = $target_path;//生成文件
		$image->jpeg_quality = 100;//生成图片质量
		//图片裁切
		if($image->crop($new_x1,$new_y1,$new_x2,$new_y2)){
			$fileinfo['filename']    = $source_info['basename'];//原文件名
			$fileinfo['savename']    = $filename;//保存文件名
			$fileinfo['filepath']    = '/' . $target_path;
			$fileinfo['ext']         = $source_info['extension'];
			$fileinfo['size']        = filesize($target_path);
			$fileinfo['create_time'] = time();
			$fileinfo['user_id']     = $user_id;
			$model = D('File');
			$model->add($fileinfo);
			//文件ID
			$file_id = $model->getLastInsID();
			return $file_id;
		}
		return false;
	}
}
